<?php
/**
 * Created by PhpStorm.
 * User: lenovo
 * Date: 2020/6/18
 * Time: 16:35
 */

namespace App\Services;
use App\Logic\Tool;
use EasySwoole\EasySwoole\Config;
use EasySwoole\Component\TableManager;
/**用于和中间服务器做数据交互
 * Class MasterService
 * @package App\Services
 */
class MasterService
{
    /**
     * @param $onlineData
     * @return bool
     */
    public function online($onlineData){
         #通知中间服务器在线信息
        go(function () use ($onlineData){
        $host = Config::getInstance()->getConf('APP.MASTER.host');
        $url = "http://{$host}/Server/Online";
        $client = new \EasySwoole\HttpClient\HttpClient($url);
        $response = $client->post($this->reqDataMaker($onlineData));
        if($response->getErrCode()){
            return false;
        }
        return true;
        });
    }

    /**
     * @param $onlineData
     * @return bool
     */
    public function offline($offlineData){
        $host = Config::getInstance()->getConf('APP.MASTER.host');
        $url = "http://{$host}/Server/Offline";
         $client = new \EasySwoole\HttpClient\HttpClient($url);
        $response = $client->post($this->reqDataMaker($offlineData));

        if($response->getErrCode()){
            return false;
        }
        return true;
    }

    /**
     * 获取用户在线信息
     */
    public function getUserOnlineInfo($userId){
        $host = Config::getInstance()->getConf('APP.MASTER.host');
        $url = "http://{$host}/User";
        $client = new \EasySwoole\HttpClient\HttpClient($url);
        $form['user_id'] = $userId;

        $response = $client->post($this->reqDataMaker($form));

        if($response->getErrCode()){
            return false;
        }
        $reponseArr = json_decode($response->getBody(),true);
        if(!isset($reponseArr['result'])){
            return false;
        }
        $userOnlineData = HelpService::aesDecrypt($reponseArr['result']);
        if(empty( $userOnlineData)){
            return false;
        }
        return  $userOnlineData;
    }

    /**生成请求参数
     * @param $form
     */
    public function reqDataMaker($form){
        $timestamp = HelpService::msectime();
        $nonce = HelpService::msectime().HelpService::createNonce(6);
        $content = HelpService::aesEncrypt(json_encode($form));
        $sign = md5($content.$timestamp.$nonce);

        $newForm['timestamp'] = $timestamp;
        $newForm['nonce'] = HelpService::aesEncrypt($nonce);
        $newForm['content'] = $content;
        $newForm['sign'] = $sign;
          return  $newForm;
    }
}